#include "login_dialog.h"
#include "ui_login_dialog.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QCryptographicHash>

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog) {
    ui->setupUi(this);
    setWindowTitle("进销存管理系统 - 登录");
    setFixedSize(400, 300);
    
    connect(ui->loginButton, &QPushButton::clicked, this, &LoginDialog::onLoginButtonClicked);
    connect(ui->cancelButton, &QPushButton::clicked, this, &LoginDialog::onCancelButtonClicked);
}

LoginDialog::~LoginDialog() {
    delete ui;
}

void LoginDialog::onLoginButtonClicked() {
    QString username = ui->usernameEdit->text().trimmed();
    QString password = ui->passwordEdit->text();
    
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入用户名和密码！");
        return;
    }
    
    if (authenticateUser(username, password)) {
        accept();
    } else {
        QMessageBox::warning(this, "错误", "用户名或密码错误！");
        ui->passwordEdit->clear();
        ui->passwordEdit->setFocus();
    }
}

void LoginDialog::onCancelButtonClicked() {
    reject();
}

bool LoginDialog::authenticateUser(const QString &username, const QString &password) {
    QSqlQuery query;
    query.prepare("SELECT password, role FROM users WHERE username = ?");
    query.addBindValue(username);
    
    if (query.exec() && query.next()) {
        QString storedPassword = query.value(0).toString();
        // 在实际应用中应该使用加密验证
        if (storedPassword == password) {
            return true;
        }
    }
    return false;
}
